import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Space } from 'antd';

import { store } from '@/store';

import { workTaskManagementJudge } from '@/services/bizApi/jixiaojixiaoguanlibiaojiekou';

type BizObject = BIZAPI.WorkTaskManagementEntity;

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EvaluationRef = {
  open: (
    arg: EditOpenBaseArgs & {
      rowData: BizObject;
    }
  ) => void;
};

export type EditProps = {};

const Evaluation: React.ForwardRefRenderFunction<EvaluationRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EvaluationRef['open']>[0]>();
  const submit = useRequest(
    async ({ planExecutionTime, planReviewTime, ...values }) => {
      const query = {
        ...values,
        id: args?.rowData?.id
      };

      await workTaskManagementJudge(query);

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success('操作成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        form.resetFields();
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title="评价"
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSave}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
      >
        <Form.Item
          label="评价详情"
          name="evaluationDetails"
          rules={[
            {
              required: true,
              message: '请输入评价详情'
            }
          ]}
        >
          <Input.TextArea style={{ width: '100%' }} placeholder="请输入评价详情" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Evaluation);
